/**
 * 
 */
package it.rainbowbreeze.polygen.ui;

import it.rainbowbreeze.libs.logic.RainbowSendStatisticsTask;
import it.rainbowbreeze.libs.ui.actionbar.RainbowActionBarBaseFragmentActivity;
import it.rainbowbreeze.polygen.R;
import it.rainbowbreeze.polygen.common.AppEnv;
import it.rainbowbreeze.polygen.common.LogFacility;
import it.rainbowbreeze.polygen.data.AppPreferencesDao;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * @author rainbowbreeze
 *
 */
public class MainActivity extends RainbowActionBarBaseFragmentActivity
implements CategoriesFragment.OnCategorySelectedListener, RefreshNotification {
    
    private static final String KEY_LAST_CATEGORY = "LastCategory";

    private LogFacility mLogFacility;
    private ActivityHelper mActivityHelper;

    private SentenceViewerFragment mFraSentenceViewer;
    private CategoriesFragment mFraCategories;
    private String mLastCategory;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.actmain);
        
        AppEnv appEnv = AppEnv.i(getApplicationContext());
        mLogFacility = appEnv.getLogFacility();
        mActivityHelper = appEnv.getActivityHelper();
        AppPreferencesDao appPreferencesDao = appEnv.getAppPreferencesDao();
        mFraSentenceViewer = (SentenceViewerFragment) getSupportFragmentManager().findFragmentById(R.id.main_fraSentenceViewer);
        mFraCategories = (CategoriesFragment) getSupportFragmentManager().findFragmentById(R.id.main_fraCategories);
        
        //register app run
        if (null == savedInstanceState) {
            //send statistics data first time the app runs
            RainbowSendStatisticsTask statsTask = new RainbowSendStatisticsTask(
                    mLogFacility,
                    mActivityHelper,
                    this,
                    AppEnv.STATISTICS_WEBSERVER_URL,
                    AppEnv.APP_INTERNAL_NAME,
                    AppEnv.APP_INTERNAL_VERSION,
                    String.valueOf(appPreferencesDao.getUniqueId()));
            Thread t = new Thread(statsTask);
            t.start();
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_LAST_CATEGORY, mLastCategory);
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mLastCategory = savedInstanceState.getString(KEY_LAST_CATEGORY);
    }

    @Override
    public void onCategorySelected(String category) {
        mLastCategory = category;
        mFraSentenceViewer.updateText(category);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.mnuactionbar, menu);
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public void onBackPressed() {
        if (!mFraCategories.goBack()) {
            super.onBackPressed();
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean processed;
        
        switch (item.getItemId()) {
            case android.R.id.home:
                //TODO
                processed = true;
                break;
            
            case R.id.actionbar_menu_share:
                shareText();
                processed = true;
                break;

            case R.id.actionBarCompat_menu_refresh:
                if (!TextUtils.isEmpty(mLastCategory) && null != mFraSentenceViewer) {
                    mFraSentenceViewer.updateText(mLastCategory);
                }
                processed = true;
                break;

            case R.id.actionbar_menu_about:
                mActivityHelper.openAbout(this, AppEnv.APP_INTERNAL_NAME, AppEnv.APP_DISPLAY_VERSION, AppEnv.EMAIL_FOR_ERROR_LOG);
                processed = true;
                break;

            default:
                processed = super.onOptionsItemSelected(item);
                break;
        }
        return processed;
    }

    /* (non-Javadoc)
     * @see it.rainbowbreeze.polygen.ui.RefreshNotification#startRefresh()
     */
    @Override
    public void startRefresh() {
        getActionBarHelper().setRefreshActionItemState(true);
    }

    /* (non-Javadoc)
     * @see it.rainbowbreeze.polygen.ui.RefreshNotification#stopRefresh()
     */
    @Override
    public void stopRefresh() {
        getActionBarHelper().setRefreshActionItemState(false);
    }

    
    private void shareText() {
        //get text from the right fragment
        String shareText = mFraSentenceViewer.getText();
        
        if (TextUtils.isEmpty(shareText)
                || shareText.equals(getString(R.string.common_msgRefreshing))
                || shareText.equals(getString(R.string.common_msgSelectCategory))) {
            Toast.makeText(this, R.string.common_msgNothingToShare, Toast.LENGTH_SHORT).show();
            return;
        }
        
        Intent intent=new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        // Add data to the intent, the receiving app will decide what to do with it.
        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.common_emailSubject));
        String emailBody = getString(R.string.common_emailBody);
        emailBody = emailBody.replace("__SENTENCE__", shareText);
        intent.putExtra(Intent.EXTRA_TEXT, shareText);
        startActivity(Intent.createChooser(intent, getString(R.string.common_shareIntentText)));
    }


}
